package org.java8newfeature.stream;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class Section12 {
    public static void main(String[] args) {
        String k = "key";
        HashMap<String, Integer> map = new HashMap<String, Integer>() {{
                put(k, 1);
            }};
       map.merge(k,2,Integer::max);
        System.out.println(map.get(k)+"map.get(key)");

        System.out.println(map.size()+ "map.size");
        System.out.println(map.get(k));


        map.merge(k,2,(oldVal,newVal)->oldVal+newVal);
        System.out.println(map.get(k));

        map.merge(k,10,Integer::sum);
        System.out.println(map.get(k));

// 创建一个Map，并填入数据
        Map<String, Integer> codes = new HashMap<>();
        codes.put("United States", 1);
        codes.put("Germany", 49);
        codes.put("France", 33);
        codes.put("China", 86);
        codes.put("Pakistan", 92);


        List<Map.Entry<String, Integer>> collect1 = codes.entrySet().stream().sorted((e1, e2) -> e1.getValue() - e2.getValue()).collect(Collectors.toList());
        System.out.println("codes根据值排序 = "+collect1);

  /*      LinkedHashMap<String, Integer> sortedMap = codes.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByKey().reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldVal, newVal) -> oldVal,
                        LinkedHashMap::new
                ));

        sortedMap.entrySet().forEach(System.out::println);*/

        LinkedHashMap<String, Integer> collect = codes.entrySet().stream()
                .sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
                .collect(Collectors.toMap(
                        map1 -> map1.getKey(),
                        map1 -> map1.getValue(),
                        (oldVal, newVal) -> oldVal, LinkedHashMap::new
                ));

        collect.entrySet().forEach(System.out::println);

    }
}
